package com.lnold.redis.config.controller;


import com.lnold.redis.config.Config;
import com.lnold.redis.config.ConfigService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/config")
public class ConfigWebController {
    @Autowired
    private ConfigService configService;
    //...

    @GetMapping("/")
    public String index(Model model) {
        Map<String, String> configs = configService.getAllConfigs();
        List<Config> configList = new ArrayList<>();
        for (Map.Entry<String, String> entry : configs.entrySet()) {
            configList.add(new Config(entry.getKey(), entry.getValue()));
        }
        model.addAttribute("configs", configList);
        return "index";
    }


    @PostMapping("/add")
    public String addConfig(@RequestParam("key") String key, @RequestParam("value") String value) {
        configService.setConfigValue(key, value);
        // 发布配置更新消息
        configService.publishUpdate(key);
        return "redirect:/config/";
    }

    @GetMapping("/edit/{name}")
    public String editConfigForm(@PathVariable String name, Model model) {
        String value = configService.getConfigValue(name);
        Config config = new Config(name, value);
        model.addAttribute("config", config);
        return "edit_form";
    }

    @PostMapping("/edit/{name}")
    public String editConfig(@PathVariable String name, @RequestParam String value) {
        configService.setConfigValue(name, value);
        // 发布配置更新消息
        configService.publishUpdate(configService.getConfigValue(name));
        return "redirect:/config/";
    }

    @PostMapping("/del/{name}")
    public String deleteConfig(@PathVariable String name) {
        configService.deleteConfigValue(name);
        // 发布配置更新消息
        configService.publishUpdate(name);
        return "redirect:/config/";
    }


    @PostMapping("/import")
    public ResponseEntity<Void> importConfig(@RequestParam("file") MultipartFile file) {
        try {
            File tempFile = File.createTempFile("temp-import", ".json");
            FileCopyUtils.copy(String.valueOf(file.getInputStream()), new FileWriter(tempFile));

            configService.importConfig(tempFile);

            tempFile.delete();
            return ResponseEntity.ok().build();
        } catch (IOException e) {
            e.printStackTrace();
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
        }
    }

    @GetMapping("/export")
    public void exportConfig(HttpServletResponse response) {
        try {
            String EXPORT_FILE_PATH = "config-export.json";
            File configFile = new File(EXPORT_FILE_PATH);
            configService.exportConfig(configFile);

            response.setContentType("application/octet-stream");
            response.setHeader("Content-Disposition", "attachment; filename=" + configFile.getName());
            FileCopyUtils.copy(new FileReader(configFile), response.getWriter());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


}